package com.yjw.demo.pattern.singleton;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注册式
 * 
 * @author yinjianwei
 * @date 2018/12/05
 */
public class Register {

    private Register() {}

    private final Map<String, Object> registerMap = new ConcurrentHashMap<>();

    public Object getInstance(String name) {

        // 参考Spring源码DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory<?> singletonFactory)
        if (name == null) {
            throw new RuntimeException("name不能为空");
        }
        synchronized (this.registerMap) {
            Object singletonObject = registerMap.get(name);
            if (singletonObject == null) {
                try {
                    singletonObject = Class.forName(name).newInstance();
                } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
                registerMap.put(name, singletonObject);
            }
            return singletonObject;
        }
    }

}
